package com.qiyou.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qiyou.dao.IUserDao;
import com.qiyou.dao.factory.DaoFactory;
import com.qiyou.entity.User;

/**
 * 用户登录
 * 
 * @author 赛艳志
 *
 */
@WebServlet("/UserLogin")
public class UserLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserLogin() {
        super();
    }
    
    /**
     * 检测用户是否存在
     * 
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return 用户存在true;不存在 false
     * @throws UnsupportedEncodingException
     */
    public boolean isUserExist(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        IUserDao userDao = DaoFactory.getUserDao();
        
        String userID = request.getParameter("username");
        User user = null;
        try {
            user = userDao.getUser(userID);
        } catch (SQLException e) {
        }
        
        return null == user ? false : true;
        
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    request.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html;charset=UTF-8");
	    
	    IUserDao userDao = DaoFactory.getUserDao();
	    
        String userId = request.getParameter("username");
        String userPwd = request.getParameter("password");
        
        User user = new User();
        user.setID(userId);
        user.setPassword(userPwd);
        
        User result = null;
        
        try {
            result = userDao.getUser(user);
        } catch (SQLException e) {
        }
        
        if(null != result){
            request.getSession().setAttribute("user", result);
            request.getRequestDispatcher("index.jsp")
                    .forward(request, response);
        }else{
            request.setAttribute("msg", "账号或密码有错，请确认！");
            request.getRequestDispatcher("login.jsp")
                    .forward(request, response);
        }
	}
}
